package it.izsto.servlet;

import it.izsto.fe.bean.DettaglioBean;

import java.io.FileNotFoundException;
import java.io.IOException;

import javax.faces.FactoryFinder;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class DownloadPdf
 */
public class DownloadPdf extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	private Logger log = Logger.getLogger(this.getClass());
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadPdf() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		ServletOutputStream op = null;
		
		
		try {
			
//			FacesContext fc = getFacesContext(request, response);
			
			DettaglioBean dettaglioBean = (DettaglioBean) request.getSession().getAttribute("dettaglioBean");
						
			// da correggere byte[] pdfByte = dettaglioBean.getPdfItem().getSigfrmrptpdf(); // deve contenere i 
			
			op = response.getOutputStream();
			response.setContentType("application/pdf");
			response.setHeader("Content-Disposition", "inline; filename=\"documento.pdf\"");
			// da correggere op.write(pdfByte);
			
		} catch (FileNotFoundException e) {
			log.error("File not found", e);
			try {
				response.getWriter().print("Pdf non trovato");
			} catch (Exception ex) {
				log.error("generic error", ex);
				response.getWriter().print("Errore nel recuperare il pdf");
			}
		} catch (Exception e) {
			log.error("Errore generico", e);
		} finally {
			if(op != null)
			{
				op.flush();
				op.close();
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	 protected FacesContext getFacesContext(HttpServletRequest request, HttpServletResponse response) {
	        FacesContext facesContext = FacesContext.getCurrentInstance();
	        if (facesContext == null) {
	 
	            FacesContextFactory contextFactory  = (FacesContextFactory)FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
	            LifecycleFactory lifecycleFactory = (LifecycleFactory)FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
	            Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
	 
	            facesContext = contextFactory.getFacesContext(request.getSession().getServletContext(), request, response, lifecycle);
	 
	            // Set using our inner class
	            InnerFacesContext.setFacesContextAsCurrentInstance(facesContext);
	 
	            // set a new viewRoot, otherwise context.getViewRoot returns null
	            UIViewRoot view = facesContext.getApplication().getViewHandler().createView(facesContext, "");
	            facesContext.setViewRoot(view);               
	        }
	        return facesContext;
	    }
	 
	// You need an inner class to be able to call FacesContext.setCurrentInstance
	    // since it's a protected method
	    private abstract static class InnerFacesContext extends FacesContext {
	        protected static void setFacesContextAsCurrentInstance(FacesContext facesContext) {
	            FacesContext.setCurrentInstance(facesContext);
	        }
	    }   
}
